package org.dromara.common.minio.utils.file;

import io.minio.*;
import io.minio.http.Method;
import org.dromara.common.core.utils.SpringUtils;
import org.dromara.common.minio.utils.ServletUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

public class MinioUtil {
    /**
     * 上传文件
     *
     * @param bucketName 桶名称
     * @param fileName
     * @throws IOException
     */
    public static String uploadFile(String bucketName, String fileName, MultipartFile multipartFile) throws IOException
    {
        String url = "";
        MinioClient minioClient = SpringUtils.getBean(MinioClient.class);
        try (InputStream inputStream = multipartFile.getInputStream())
        {
          // 检查存储桶是否存在，如果不存在则创建
          boolean isBucketExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
          if (!isBucketExist) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
          }
          // 上传文件
          minioClient.putObject(PutObjectArgs.builder()
            .bucket(bucketName)
            .object(fileName)
            .stream(inputStream, multipartFile.getSize(), -1)
            .contentType(multipartFile.getContentType())
            .build());
          // 获取预签名 URL
          url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
            .bucket(bucketName)
            .object(fileName)
            .method(Method.GET)
            .build());
          // 去掉 URL 中的查询参数
          url = url.substring(0, url.indexOf('?'));
          return ServletUtils.urlDecode(url);
        }
/*        {
            minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(fileName).stream(inputStream, multipartFile.getSize(), -1).contentType(multipartFile.getContentType()).build());
            url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder().bucket(bucketName).object(fileName).method(Method.GET).build());
            url = url.substring(0, url.indexOf('?'));
            return ServletUtils.urlDecode(url);
        }*/
        catch (Exception e)
        {
            throw new IOException(e.getMessage(), e);
        }
    }
}
